package ui

import (
	"gioui.org/layout"
	"gioui.org/widget"
	"gioui.org/widget/material"
	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
	"log"
)

type ResponseEdit struct {
	*widget.Editor
	textEdit *material.EditorStyle

	buf         []byte
	dirty       bool
	text        string
	lastCharset string
}

func NewResponseEdit(th *material.Theme, hint string) *ResponseEdit {
	editor := widget.Editor{
		ReadOnly:   true,
		SingleLine: false,
	}
	textEdit := material.Editor(th, &editor, hint)
	return &ResponseEdit{
		Editor:   &editor,
		textEdit: &textEdit,
	}
}

func (r *ResponseEdit) Write(p []byte) (n int, err error) {
	if len(p) == 0 {
		return 0, nil
	}

	r.buf = append(r.buf, p...)
	r.text = ""
	r.dirty = true
	return len(p), nil
}

func (r *ResponseEdit) SetContent(p []byte) {
	r.buf = append([]byte{}, p...)
	r.text = ""
	r.dirty = true
}

func (r *ResponseEdit) SetCharset(charset string) {
	if charset != r.lastCharset {
		r.lastCharset = charset
		r.dirty = true
	}
}

func (r *ResponseEdit) refreshDisplay() {
	if !r.dirty {
		return
	}

	var err error
	var decoded []byte

	switch r.lastCharset {
	case "gbk":
		decoder := simplifiedchinese.GBK.NewDecoder()
		decoded, _, err = transform.Bytes(decoder, r.buf)
		if err != nil {
			log.Println(err)
			decoded = []byte(err.Error())
		}
	default:
		decoded = r.buf
	}

	r.text = string(decoded)
	r.Editor.SetText(r.text)
	r.dirty = false
}

func (r *ResponseEdit) Layout(gtx layout.Context) layout.Dimensions {
	if r.dirty && r.buf != nil && len(r.buf) != 0 {
		r.refreshDisplay()
	}

	return r.textEdit.Layout(gtx)
}

func (r *ResponseEdit) Clear() {
	r.buf = r.buf[:0]
	r.dirty = true
}

func (r *ResponseEdit) Content() []byte {
	return append([]byte{}, r.buf...)
}
